package com.example.mysongplayer;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener {
    private static SeekBar seekB;
    private static TextView tv_progress, tv_total, thesong_name, thesong_singer;
    private static ImageButton btn_pause;
    private MusicService.MusicControl musicControl;
    String name, singer;
    Intent intent1, intent2;
    MyServiceConn conn;
    private boolean isUnbind = false;//记录服务是否被解绑
    private int pauseIndex = 0;//记录按钮为播放还是暂停，奇数暂停，偶数播放

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        intent1 = getIntent();
        init();
    }

    private void init(){
        //绑定各个组件
        tv_progress = (TextView)findViewById(R.id.tv_progress);
        tv_total = (TextView)findViewById(R.id.tv_total);
        seekB = (SeekBar)findViewById(R.id.seekB);
        thesong_name = (TextView)findViewById(R.id.thesong_name);
        thesong_singer = (TextView)findViewById(R.id.thesong_singer);

        findViewById(R.id.btn_pause).setOnClickListener(this);
        findViewById(R.id.btn_backlist).setOnClickListener(this);

        //接收来自intent1的消息
        name = intent1.getStringExtra("song_name");
        singer = intent1.getStringExtra("singer");
        //写入TextView中
        thesong_name.setText(name);
        thesong_singer.setText(singer);

        //创建意图对象
        intent2 = new Intent(this, MusicService.class);
        //创建服务连接对象
        conn = new MyServiceConn();
        //绑定服务
        bindService(intent2, conn, BIND_AUTO_CREATE);
        //给滑动条添加事件监听
        seekB.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
                //进度条改变时调用此方法
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {//滑动条开始时调用
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar){//滑动条停止时调用
                //根据拖动的进度调整音乐播放进度
                //获取进度条的进度
                int progress = seekBar.getProgress();
                //改变播放进度
                musicControl.seekTo(progress);
            }

        });

    }

    //创建消息处理器对象
    public static Handler handler = new Handler(){
        //在主线程中处理子线程发送过来的消息
        @Override
        public void handleMessage(Message msg){
            //获取从子线程发送过来的音乐播放进度
            Bundle bundle = msg.getData();
            int duration = bundle.getInt("duration");
            int currentPosition = bundle.getInt("currentPosition");
            seekB.setMax(duration);
            seekB.setProgress(currentPosition);
            //歌曲总时长
            int minute = duration/1000/60;
            int second = duration/1000%60;
            String strMinute = null;
            String strSecond = null;
            //歌曲中的分<10
            if(minute < 10){
                //在分的前面加一个0
                strMinute = "0" + minute;
            }else {
                strMinute = minute+"";
            }
            //歌曲中的秒 <10
            if(second < 10){
                strSecond = "0" + second;
            }else{
                strSecond = second + "";
            }
            tv_total.setText(strMinute + ":" + strSecond);

            //获取音乐的总时长
            minute = currentPosition/1000/60;
            second = currentPosition/1000%60;
            //歌曲中的分<10
            if(minute < 10){
                //在分的前面加一个0
                strMinute = "0" + minute;
            }else {
                strMinute = minute+"";
            }
            //歌曲中的秒 <10
            if(second < 10){
                strSecond = "0" + second;
            }else{
                strSecond = second + "";
            }
            tv_progress.setText(strMinute + ":" + strSecond);

        }
    };

    //实现连接服务
    class MyServiceConn implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName name, IBinder service){
            musicControl = (MusicService.MusicControl) service;
        }
        @Override
        public void onServiceDisconnected(ComponentName name){}

    }

    //判断服务是否解绑
    private void unbind(boolean isUnbind){
        if(!isUnbind){
            //暂停播放音乐
            musicControl.pausePlay();
            //解绑服务
            unbindService(conn);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View v){
        btn_pause = (ImageButton)findViewById(R.id.btn_pause);
        //点击暂停/播放按钮
        if (v.getId() == R.id.btn_pause){
            //第一次点击，开始播放
            if(pauseIndex == 0) {
                pauseIndex++;
                btn_pause.setImageResource(R.mipmap.stop);
                String path = intent1.getStringExtra("path");
                musicControl.play(path);
            }else if(pauseIndex % 2 == 1){
                pauseIndex++;
                btn_pause.setImageResource(R.mipmap.start);
                musicControl.pausePlay();
            }else{//index为偶数，继续播放
                pauseIndex++;
                btn_pause.setImageResource(R.mipmap.stop);
                musicControl.continuePlay();
            }
        }
        //点击返回文件列表，退出播放
        if(v.getId() == R.id.btn_backlist){
            unbind(isUnbind);
            isUnbind = true;
            Intent intent3 = new Intent();
            intent3.setClass(MusicActivity.this, Music_List.class);
            startActivity(intent3);
        }
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        //解绑服务
        unbind(isUnbind);
    }


}